package org.ribizli.basicgameserver.data;

import java.util.List;

import org.hibernate.Session;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class TopList {
	private String username;

	public TopList() {
		this(null);
	}

	public TopList(String user) {
		this.username = user;
	}

	@SuppressWarnings("unchecked")
	public JSONObject getTopScores() throws JSONException {
		JSONObject obj = new JSONObject();
		Session s = HibernateUtil.getSession();
		List<User> l = s.createQuery("select u from User u order by u.score desc, u.username asc")
				.setMaxResults(10).list();
		JSONArray top10 = new JSONArray();
		obj.put("top10", top10);
		int containsUser = -1;
		for (int i = 0; i < l.size(); i++) {
			User user = l.get(i);
			top10.put(new JSONObject().put("username", user.getUsername()).put(
					"score", user.getScore()));
			if (username != null && username.equals(user.getUsername())) {
				containsUser = i;
			}
		}
		if (username != null && containsUser == -1) {
			User u = User.findUser(username);
			if (u != null) {
				obj.put("user", new JSONObject()
					.put("username", u.getUsername())
					.put("score", u.getScore())
				);
			}
		} else if (containsUser > -1) {
			User u = l.get(containsUser);
			obj.put("user", new JSONObject()
					.put("username", u.getUsername())
					.put("score",	u.getScore()))
				.put("userIndex", containsUser
			);
		}
		s.close();
		return obj;
	}
}
